<template>
  <div class="contianer">
    <el-row :gutter="16" style="left:10%">
      <el-col :span="16">
        <el-form
          :model="tableData"
          :rules="rules"
          ref="tableData"
          label-width="100px"
          class="demo-ruleForm"
        >
          <table>
            <tr>
              <td colspan="2">
                <el-form-item label="文章标题" prop="title">
                  <el-input v-model="tableData.title" placeholder="请输入标题"></el-input>
                </el-form-item>
              </td>
            </tr>
            <tr>
              <td colspan="2">
                <el-form-item label="正文内容" prop="content">
                  <quill-editor
                    class="editor"
                    v-model="tableData.content"
                    ref="content"
                    :options="editorOption"
                    @blur="onEditorBlur($event)"
                    @focus="onEditorFocus($event)"
                    @change="onEditorChange($event)"
                  >
                  </quill-editor>
                </el-form-item>
              </td>
            </tr>
            <tr>
              <td colspan="2">
                <el-form-item label="文章标签">
                  <div class="block">
                    <el-cascader
                      placeholder="点击添加标签"
                      :options="options"
                      :props="{ multiple: true }"
                      v-model="tagList"
                      :show-all-levels="false"
                      id="tagList"
                      clearable
                      filterable
                    ></el-cascader>
                  </div>
                </el-form-item>
              </td>
            </tr>
            <tr>
              <td style="width: 25%">
                <el-form-item label="文章封面" id="coverForm">
                  <el-upload
                    action="api/util/uploadImg"
                    list-type="picture-card"
                    :auto-upload="true"
                    :on-change="handleExceed"
                    :headers="MyHeader"
                    :file-list="fileList"
                    :limit="1"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                    name="imgFile"
                  >
                    <i slot="default" class="el-icon-plus"></i>
                    <div slot="file" slot-scope="{ file }">
                      <img
                        class="el-upload-list__item-thumbnail"
                        :src="tableData.fileUid"
                      />
                      <span class="el-upload-list__item-actions">
                        <span
                          class="el-upload-list__item-preview"
                          @click="handlePictureCardPreview(file)"
                        >
                          <i class="el-icon-zoom-in"></i>
                        </span>
                        <span
                          v-if="!disabled"
                          class="el-upload-list__item-delete"
                          @click="handleRemove(file)"
                        >
                          <i class="el-icon-delete"></i>
                        </span>
                      </span>
                    </div>
                  </el-upload>
                  <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" :src="dialogImageUrl" alt="" />
                  </el-dialog>
                </el-form-item>
              </td>
              <td style="width: 75%">
                <el-form-item label="文章摘要" prop="title" id="summary">
                  <el-input
                    v-model="tableData.summary"
                    placeholder="文章摘要"
                    type="textarea"
                    id="summaryInput"
                  ></el-input>
                </el-form-item>
              </td>
            </tr>
            <tr>
              <td colspan="2">
                <el-form-item label="是否原创">
                  <el-radio-group v-model="tableData.isOriginal">
                    <el-radio-button label="原创" ></el-radio-button>
                    <el-radio-button label="转载"></el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </td>
            </tr>
            <tr>
              <td colspan="2">
                <div class="formButton">
                  <el-form-item style="float: right">
                    <el-button type="danger" @click="resetForm('tableData')" round
                      >重置内容</el-button
                    >
                    <el-button type="success" @click="lookForm()" round>预览</el-button>
                    <el-button type="primary" @click="submitForm()" id="submitDiv" round
                      >更新博客</el-button
                    >
                  </el-form-item>
                </div>
              </td>
            </tr>
          </table>
        </el-form>
      </el-col>
      <!-- <el-col :span="8">
        <div class="left"></div>
      </el-col> -->
    </el-row>
  </div>
</template>

<script>
import { $updateArticle } from "@/assets/api/user.js";
import { $deleteUploadImg } from "@/assets/api/user.js";
import { $findBolgTag } from "@/assets/api/user.js";
export default {
  name: "addArticle",
  data() {
    return {
      MyHeader: { token: JSON.parse(sessionStorage.getItem("token")) },
      tableData: {
        id: "", //id标识
        title: "", //博客标题
        summary: "", //博客简介
        content: "", //博客内容
        tagUid: "", //标签uid
        clickCount: 0, //博客点击数
        collectCount: 0, //博客收藏数
        fileUid: "", //标题图片uid
        createdTime: "", //创建时间
        modifiedTime: "", //更新时间
        isOriginal: "原创", //原创
        author: "", //作者
        articlesPart: "", //文章出处
        openComment: "", //是否开启评论
      },
      editorOption: {},
      uploadFiles: [],
      fileList: [],
      editForm: {
        chairImg: "",
      }, //图片上传成功后返回的路径，用户回调函数

      //标签
      // dynamicTags: [],
      // inputVisible: false,
      // inputValue: '',

      tagList: [],

      options: [],

      //封面属性
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,

      //表单规则
      rules: {
        title: [
          { required: true, message: "请输入文章标题", trigger: "blur" },
          { min: 1, max: 10, message: "长度在 1 到 10 个字符", trigger: "blur" },
        ],
        content: [{ required: true, message: "请输入文章内容", trigger: "blur" }],
      },
    };
  },
  created() {
    this.getFrom();
    this.findBolgTag();
  },
  methods: {

    findBolgTag() {
      $findBolgTag().then((res) => {
        if (res.data.success) {
          this.options = res.data.data.findBolgTag;
        } else {
          this.message(res);
        }
      });
    },
    getFrom() {
      //获取文章id
      this.tableData = JSON.parse(sessionStorage.getItem("tableData"));
      this.tableData.isOriginal = this.tableData.isOriginal == 1 ? "原创" : "转载";
    },

    //提交方法
    submitForm() {
      var tagArr = [];
      for (var i = 0; i < this.tagList.length; i++) {
        tagArr[i] = this.tagList[i][1];
      }

      this.tableData.isOriginal = this.tableData.isOriginal == "原创" ? "1" : "0";
      $updateArticle({ wqunBlog: this.tableData, tagArr: tagArr }).then((res) => {
        this.$message({
          type: res.data.success ? "success" : "error",
          message: res.data.message,
        });
        if (res.data.success) {
          (this.tableData = []), (this.tagList = []), (this.editForm = []);
        }
      });
    },

    //图片上传
    handleAvatarSuccess(res) {
      this.$message({
          type:res.success?'success':'error',
          message:res.message,
        })
      if (res.success) {
        this.tableData.fileUid = res.data.resPath;
        
      }
    },
    beforeAvatarUpload(file) {
      // 设置限定格式
      const img_mimetype = ["image/jpeg", "image/jpg", "image/png"];
      const isJPG = img_mimetype.includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isJPG) {
        this.$message.error("上传头像只能是图片格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 10MB!");
        return false;
      }
      return isJPG && isLt2M;
    },

    //封面方法
    handleRemove(file) {
      //移除图片
      $deleteUploadImg({ oosImgPath: this.tableData.fileUid }).then((res) => {
        if (res.data.success) {
          this.fileList = [];
          if (this.fileList.length >= 1) {
            this.getstyle(".el-upload--picture-card").display = "none";
          } else {
            setTimeout(() => {
              this.getstyle(".el-upload--picture-card").display = "inline-block";
            }, 1150);
          }
          this.$message({ type: "success" });
        } else {
          this.$message({ type: "error" });
        }
      });
    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    getNowTime() {
      let now = new Date();
      let year = now.getFullYear(); //获取完整的年份(4位,1970-????)
      let month = now.getMonth() + 1; //获取当前月份(0-11,0代表1月)
      let today = now.getDate(); //获取当前日(1-31)
      let hour = now.getHours(); //获取当前小时数(0-23)
      let minute = now.getMinutes(); //获取当前分钟数(0-59)
      let second = now.getSeconds(); //获取当前秒数(0-59)
      let nowTime = "";
      nowTime =
        year + "-" + month + "-" + today + " " + hour + ":" + minute + ":" + second;
      return nowTime;
    },
    resetForm(formName) {
      this.$confirm("是否清空该文章编辑?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$refs[formName].resetFields();
          this.tableData = [];
          this.tagList = [];
          this.editForm = [];
          this.$message({
            type: "success",
            message: "已清空",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消操作",
          });
        });
      // if(confirm("是否清空该文章编辑？")){
      //   this.$refs[formName].resetFields();
      // }
    },

    // handleDownload(file) {
    // },
    getstyle(sname) {
      //从整个页面查找class为sname的页面
      for (var i = 0; i < document.styleSheets.length; i++) {
        var rules;
        if (document.styleSheets[i].cssRules) {
          rules = document.styleSheets[i].cssRules;
        } else {
          rules = document.styleSheets[i].rules;
        }
        for (var j = 0; j < rules.length; j++) {
          if (rules[j].selectorText == sname) {
            return rules[j].style;
          }
        }
      }
    },

    handleExceed(files, fileList) {
      this.fileList = fileList;
      if (this.fileList.length >= 1) {
        this.getstyle(".el-upload--picture-card").display = "none";
      } else {
        this.getstyle(".el-upload--picture-card").display = "inline-block";
      }
    },

    //事件
    addArticle() {},
    onEditorBlur() {},
    onEditorFocus() {
      //获得焦点事件
    },
    onEditorChange() {
      //内容改变事件
    },

    //预览
    lookForm() {
      //将信息缓存到浏览器里面

      this.tableData.createdTime = this.getNowTime();
      var arr = JSON.stringify(this.tableData);
      window.localStorage.setItem("formData", arr);
      //将封面信息传给预览界面fileList
      var fileList = JSON.stringify(this.fileList);
      window.localStorage.setItem("fileList", fileList);

      //标签组
      var tag = JSON.stringify(this.tagList);
      window.localStorage.setItem("tagList", tag);
      this.$router.push({
        name: "previewArticle",
      });
    },
  },
};
</script>

<style scoped>
.contianer {
  min-width: 1270px;
}

.left {
  background-color: #cccccc;
  min-width: 100px;
  height: 1000px;
  padding: 10px;
  margin: 2%;
  margin-left: 12%;
}

#coverForm {
  display: inline-block;
  height: 150px;
  width: 25%;
}

#summary {
  display: inline-block;
  margin-left: 5%;
  width: 95%;
  height: 150px;
}

#summaryInput {
  height: 150px;
}

#tagList {
  min-width: 500px;
}

.formButton {
  bottom: 0px;
  min-width: 900px;
}
</style>

<style>
.ql-editor {
  min-height: 300px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
